package com.daervin.cpe.utils;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @author daervin
 * @date 2019/11/19
 */
public class JsonUtil {
    private static final ObjectMapper MAPPER = new ObjectMapper();

    private JsonUtil() {
        // 工具类不可实例化
    }

    static {
        // 设计转换器转化规则-空字符串转换为NULL
        MAPPER.configure(
                DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT,
                true);

        // 忽略不识别字段
        MAPPER.configure(
                DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        MAPPER.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
    }

    /**
     * java对象转换成json字符串
     *
     * @param object 对象
     * @return json字符串
     */
    public static String toString(Object object) {
        if (object == null) {
            return "";
        }
        if (object instanceof String) {
            return object.toString();
        }

        try {
            return MAPPER.writeValueAsString(object);
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
        return null;
    }

    /**
     * 将json字符串转换成java对象
     *
     * @param jsonStr     json字符串
     * @param objectClass 指定的对象类
     * @return 指定的对象
     */
    public static <T> T toObject(String jsonStr, Class<T> objectClass) {
        try {
            return MAPPER.readValue(jsonStr, objectClass);
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
        return null;
    }

    /**
     * 将json字符串转换成java对象（集合通用）
     *
     * @param jsonStr
     * @param jsonTypeReference new TypeReference<T>(){}
     * @param <T>
     * @return
     */
    public static <T> T toObject(String jsonStr, TypeReference<T> jsonTypeReference) {
        try {
            if (jsonStr == null) {
                return null;
            }
            return MAPPER.readValue(jsonStr, jsonTypeReference == null ? new TypeReference<T>() {
            } : jsonTypeReference);
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
        return null;
    }

    /**
     * 将json字符串转换成json树
     *
     * @param jsonStr json字符串
     * @return json树
     */
    public static JsonNode toJsonNode(String jsonStr) {
        try {
            return MAPPER.readTree(jsonStr);
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
        return null;
    }
}
